const rsa= require('./rsa');
const Table= require('cli-table');
const vorpal= require('vorpal')();
let Communication= require('./Communication');
Communication= new Communication()
// console.log(Array.isArray(Communication.blockchain), 'length', Communication.blockchain.length, Communication.blockchain)
function format(arr=[]){
    if(arr.length=== 0)
        return;
    // console.log('typeof(arr)', typeof(arr), '\n!!',arr)
    if(!Array.isArray(arr))
        arr= [arr];
    const head= Object.keys(arr[0]);
    // console.log('arr[0]', arr[0])
    let table= new Table({
        head,
        // colWidth: [4, 10, 6, 4, 4, 10]
    });
    arr.map(v=>
        table.push(head.map(h=> JSON.stringify(v[h],null, 2)))
    )
    console.log(table.toString())
    // return table.toString();
}

vorpal
    .command('balance <address>', '显示余额')
    .action(function (args, cb) {
        const balance= Communication.balance(args.address);
        if(balance)
            this.log(balance, args.address);
        cb();
    });

vorpal
    .command('detail <index>', '查看详情')
    .action(function(args, cb){
        if(args.index>=0 && args.index<Communication.blockchain.length)
            this.log(
                JSON.stringify(Communication.blockchain[args.index], null, 2)
            );
        else
            this.log('区块不存在');
        cb();
    });

vorpal
    .command('trans <to> <amount>', '转账')
    .action(function(args, cb){
        const trans= Communication.transfer(rsa.pub, args.to, args.amount); //转出人是自己
        if(trans)
            format(trans);
        cb();
    });

vorpal
    .command('mine', '挖矿')
    .action(function(args, cb) {
        const bc= Communication.mine()
        if(bc)
            format(bc);
        cb();
    })

vorpal
    .command('chain', '查看区块链')
    .action(function(args, cb) {
        format(Communication.blockchain);
        cb();
    })

vorpal
    .command('peers', '查看节点列表')
    .action(function(args, cb) {
        format(Communication.peers);
        cb();
    })

vorpal
    .command('chat <message>', '群聊')
    .action(function(args, cb) {
        Communication.broadcast({
            type: 'hello',
            data: args.message,
        });
        cb();
    })

// vorpal
//     .command('foo', '显示 bar')
//     .action(function(args, cb) {
//         this.log('bar')
//         cb()
//     })

console.log('欢迎使用我的区块链')
vorpal.exec('help')

vorpal
    .delimiter('->')
    .show()